<template>
  <el-input class="send-code" :model-value="modelValue" @update:model-value="$event => $emit('update:modelValue', $event)" v-bind="$attrs">
    <template #suffix>
      <el-button v-if="countDownSecond == 0" type="primary" link @click="handleSendCode">获取验证码</el-button>
      <span v-else>{{ countDownSecond }}s</span>
    </template>
  </el-input>
</template>
<script setup>
import { ref, onBeforeUnmount } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:modelValue', 'sendCode'])

const countDownSecond = ref(0)

let timer = null
const timerCountDown = () => {
  timer = setInterval(() => {
    if (countDownSecond.value > 0 ) {
      countDownSecond.value--
    } else {
      clearInterval(timer)
    }
  }, 1000);
}

const startCountDown = (start) => {
  if (start) {
    countDownSecond.value = 60
    timerCountDown()
  }
}

const handleSendCode = () => {
  emits('sendCode', startCountDown)
}

onBeforeUnmount(() => {
  clearInterval(timer)
})

</script>

<style lang="scss" scoped>
.send-code{
  :deep(.el-input-group__append) {
    background-color: transparent;
  }
}
</style>